package com.kejiguan.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.kejiguan.ui.adapter.SheduleObjectAdapterNew;
import com.kejiguan.ui.adapter.SheduleOperationAdapter;
import com.kejiguan.ui.adapter.SheduleTimeTypeAdapter;
import com.kejiguan.ui.adapter.SheduleWeekAdapter;
import com.kejiguan.ui.adapter.TimeSpinnerAdapter;
import com.kejiguan.ui.dialog.CommDialogUtil;
import com.kejiguan.ui.model.DisplayArea;
import com.kejiguan.ui.model.ExhibitionNeItem;
import com.kejiguan.ui.model.Shedule;
import com.kejiguan.ui.model.SheduleActionType;
import com.kejiguan.ui.model.SheduleObject;
import com.kejiguan.ui.model.SheduleTypeModel;
import com.kejiguan.ui.model.WeekItem;
import com.kejiguan.ui.presenter.TimeSheduleActivityPresenter;
import com.kejiguan.ui.response.DelSheduleResponse;
import com.kejiguan.ui.response.ModifySheduleResponse;
import com.kejiguan.ui.util.CacheDataUtil;
import com.kejiguan.ui.util.CommonDate;
import com.kejiguan.ui.widget.NoScrollGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by YYY on 16/8/19.
 */
public class ModifyTimingSheduleActivity extends Activity implements View.OnClickListener {


    private TimeSheduleActivityPresenter mPresenter;

    private EditText sheduleNameInput;
    private Spinner sheduleTypeSpinner;
    private Spinner weekSpinner;

    private Spinner hourSpinner, minSpinner, secSpinner;
    private Spinner sheduleActionSpinner;
    private NoScrollGridView sheduleObjectList;
    private View modifyBtn, delBtn, cancelBtn;

    private List<SheduleObject> sheduleObjects = new ArrayList<>(0);
    private String selectObjectIds;
    private SheduleObjectAdapterNew sheduleObjectAdapter;


    private Shedule shedule;


    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        getIntentData();
        if (null == shedule) {
            finish();
        }
        setContentView(R.layout.activity_modify_timing_shedule_layout);
        mPresenter = new TimeSheduleActivityPresenter();
        mPresenter.onCreate(ModifyTimingSheduleActivity.this);

        EventBus.getDefault().register(this);
        initViews();
        setPreShedule();
    }

    private void getIntentData() {
        shedule = (Shedule) getIntent().getSerializableExtra("shedule");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initSelectObjectsBySelectIds() {
        sheduleObjects.clear();

        if (TextUtils.isEmpty(selectObjectIds)) {
            SheduleObject sheduleObject = new SheduleObject();
            sheduleObject.setId("");
            sheduleObject.setName("新增");

            sheduleObjects.add(sheduleObject);
        } else {

            if (selectObjectIds.contains("ZALL")) {
                SheduleObject sheduleObject = new SheduleObject();
                sheduleObject.setId("ZALL");
                sheduleObject.setName("全部");

                sheduleObjects.add(sheduleObject);
            } else {
                List<DisplayArea> displayAreas = CacheDataUtil.getInstance().getDisplayAreas();

                for (DisplayArea displayArea : displayAreas) {
                    if (selectObjectIds.contains(displayArea.getDisplayId())) {

                        SheduleObject sheduleObject = new SheduleObject();
                        sheduleObject.setId(displayArea.getDisplayId());
                        sheduleObject.setName(displayArea.getDisplayName());

                        sheduleObjects.add(sheduleObject);
                    } else {
                        if (null != displayArea.getExhibitionNeItems()) {
                            for (ExhibitionNeItem exhibitionNeItem : displayArea.getExhibitionNeItems()) {
                                if (selectObjectIds.contains(exhibitionNeItem.getExhibitionId())) {
                                    SheduleObject sheduleObject = new SheduleObject();
                                    sheduleObject.setId(exhibitionNeItem.getExhibitionId());
                                    sheduleObject.setName(exhibitionNeItem.getExhibitionName());

                                    sheduleObjects.add(sheduleObject);
                                }
                            }
                        }
                    }
                }
            }

        }
    }


    private void initViews() {

        sheduleNameInput = (EditText) findViewById(R.id.shedule_name_input);
        sheduleTypeSpinner = (Spinner) findViewById(R.id.type_select);
        weekSpinner = (Spinner) findViewById(R.id.week_select);
        hourSpinner = (Spinner) findViewById(R.id.hour_select);
        minSpinner = (Spinner) findViewById(R.id.min_select);
        secSpinner = (Spinner) findViewById(R.id.sec_select);
        sheduleActionSpinner = (Spinner) findViewById(R.id.action_select);
        sheduleObjectList = (NoScrollGridView) findViewById(R.id.object_select);
        modifyBtn = findViewById(R.id.modify_shedule_confirm_btn);
        cancelBtn = findViewById(R.id.modify_shedule_cancel_btn);
        delBtn = findViewById(R.id.del_shedule_cancel_btn);

        sheduleTypeSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        weekSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        hourSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        minSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        secSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        sheduleActionSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);

        modifyBtn.setOnClickListener(this);
        delBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        hourSpinner.setAdapter(new TimeSpinnerAdapter(ModifyTimingSheduleActivity.this, 0, 23));
        minSpinner.setAdapter(new TimeSpinnerAdapter(ModifyTimingSheduleActivity.this, 0, 59));
        secSpinner.setAdapter(new TimeSpinnerAdapter(ModifyTimingSheduleActivity.this, 0, 59));
        sheduleActionSpinner.setAdapter(new SheduleOperationAdapter(ModifyTimingSheduleActivity.this, CommonDate.actionTypes));
        weekSpinner.setAdapter(new SheduleWeekAdapter(ModifyTimingSheduleActivity.this, CommonDate.weekItems));
        sheduleTypeSpinner.setAdapter(new SheduleTimeTypeAdapter(ModifyTimingSheduleActivity.this, CommonDate.sheduleTypeModels));
        sheduleTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.e(AddTimingScheduleActivity.class.getSimpleName(), "position:" + position);
                if (position == (sheduleTypeSpinner.getAdapter().getCount() - 1)) {
                    weekSpinner.setVisibility(View.VISIBLE);
                } else {
                    weekSpinner.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sheduleObjectAdapter = new SheduleObjectAdapterNew(ModifyTimingSheduleActivity.this, sheduleObjects, ModifyTimingSheduleActivity.this);
        sheduleObjectList.setAdapter(sheduleObjectAdapter);
    }


    public void setPreShedule() {
        //任务名
        sheduleNameInput.setText(shedule.getScheduleName());
        //任务动作
        String actionType = shedule.getScheduleAction();
        if ("K".equals(actionType)) {
            sheduleActionSpinner.setSelection(0);
        } else {
            sheduleActionSpinner.setSelection(1);
        }
        //任务周期
        String sheduleType = shedule.getScheduleType();
        switch (sheduleType) {
            case "1":
                sheduleTypeSpinner.setSelection(0);
                break;
            case "2":
                sheduleTypeSpinner.setSelection(1);
                break;
            case "4":
                sheduleTypeSpinner.setSelection(2);
                break;
            default:
                String[] types = sheduleType.split(",");
                if (null != types && types.length == 2) {
                    sheduleTypeSpinner.setSelection(3);
                    switch (types[1]) {

                        case "MON":
                            weekSpinner.setSelection(0);
                            break;
                        case "TUE":
                            weekSpinner.setSelection(1);
                            break;
                        case "WED":
                            weekSpinner.setSelection(2);
                            break;
                        case "THU":
                            weekSpinner.setSelection(3);
                            break;
                        case "FRI":
                            weekSpinner.setSelection(4);
                            break;
                        case "SAT":
                            weekSpinner.setSelection(5);
                            break;
                        case "SUN":
                            weekSpinner.setSelection(6);
                            break;
                        default:
                            weekSpinner.setSelection(0);
                            break;
                    }

                } else {
                    sheduleTypeSpinner.setSelection(0);
                }
                break;
        }

        //任务对象

        selectObjectIds = shedule.getScheduleObject();
        initSelectObjectsBySelectIds();
        //时间
        String sheduleTime = shedule.getScheduleTime();
        String[] times = sheduleTime.split(":");
        String horString = times[0];
        String minString = times[1];
        String secString = times[2];
        int hor = Integer.valueOf(horString);
        int min = Integer.valueOf(minString);
        int sec = Integer.valueOf(secString);
        hourSpinner.setSelection(hor);
        minSpinner.setSelection(min);
        secSpinner.setSelection(sec);

        sheduleObjectAdapter.setSheduleObjects(sheduleObjects);
    }

    @Override
    public void onClick(View v) {


        switch (v.getId()) {
            case R.id.modify_shedule_confirm_btn:
                String sheduleName = sheduleNameInput.getText().toString();
                if (TextUtils.isEmpty(sheduleName)) {
                    Toast.makeText(ModifyTimingSheduleActivity.this, "任务名不能为空", Toast.LENGTH_SHORT).show();
                    break;
                }

                SheduleTimeTypeAdapter sheduleTimeTypeAdapter = (SheduleTimeTypeAdapter) sheduleTypeSpinner.getAdapter();
                String timeType = ((SheduleTypeModel) sheduleTimeTypeAdapter.getItem(sheduleTypeSpinner.getSelectedItemPosition())).getTypeId();
                if ("5".equals(timeType)) {
                    SheduleWeekAdapter weekAdapter = (SheduleWeekAdapter) weekSpinner.getAdapter();
                    String weekType = ((WeekItem) weekAdapter.getItem(weekSpinner.getSelectedItemPosition())).getWeekId();
                    timeType = timeType + "," + weekType;
                }

                SheduleOperationAdapter operationAdapter = (SheduleOperationAdapter) sheduleActionSpinner.getAdapter();
                String actionType = ((SheduleActionType) operationAdapter.getItem(sheduleActionSpinner.getSelectedItemPosition())).getActionId();

                int hour = hourSpinner.getSelectedItemPosition();
                int min = minSpinner.getSelectedItemPosition();
                int sec = secSpinner.getSelectedItemPosition();

                String hourS = hour < 10 ? "0" + hour : String.valueOf(hour);
                String minS = min < 10 ? "0" + min : String.valueOf(min);
                String secS = sec < 10 ? "0" + sec : String.valueOf(sec);

                Shedule newShedule = new Shedule();
                newShedule.setScheduleId(shedule.getScheduleId());
                newShedule.setScheduleName(sheduleName);
                newShedule.setScheduleType(timeType);
                newShedule.setScheduleAction(actionType);
                newShedule.setScheduleObject(selectObjectIds);
                newShedule.setScheduleNote("");
                newShedule.setScheduleState("0");
                newShedule.setScheduleTime(hourS + ":" + minS + ":" + secS);


                mPresenter.modifyShedule(newShedule);
                break;
            case R.id.modify_shedule_cancel_btn:
                finish();
                break;
            case R.id.del_shedule_cancel_btn:
                CommDialogUtil.getInstance().show(ModifyTimingSheduleActivity.this, "要删除" + shedule.getScheduleName() + "定时任务吗?", ModifyTimingSheduleActivity.this, "删除", "取消", 0);
                break;
            case R.id.object_name:
                Intent selectObjectIntent = new Intent(ModifyTimingSheduleActivity.this, SelectSheduleObjectActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("selectIds", selectObjectIds);
                selectObjectIntent.putExtras(bundle);
                startActivityForResult(selectObjectIntent, 99);
                break;
            case R.id.dialog_confirm_btn:
                CommDialogUtil.getInstance().dismiss();
                mPresenter.delShedule(shedule);
                break;
            case R.id.dialog_cancel_btn:
                CommDialogUtil.getInstance().dismiss();
                break;

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 99:
                    String result = intent.getStringExtra("selectIds");
                    selectObjectIds = new String(result);
                    initSelectObjectsBySelectIds();
                    sheduleObjectAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DelSheduleResponse response) {

        if ("0000".equals(response.getRetCode())) {

            finish();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ModifySheduleResponse response) {

        if ("0000".equals(response.getRetCode())) {
            finish();
        }
    }

}
